import { usePermissionStore } from './../store/modules/permission'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { setTitle } from '@/utils/dom'
import NProgress from 'nprogress'
import { useTagsStore } from '@/store/modules/tags'
const userStore = useUserStore()
const permissionStore = usePermissionStore()
const tagStore = useTagsStore()
let homePath = '/'
const loginPath = '/login'
const errorPath = '/404'
export const setupPermission = () => {
  router.beforeEach((to, _, next) => {
    NProgress.start()
    // *验证token
    if (userStore.token) {
      // *路由是否已经加载
      if (permissionStore.asyncRoutes.length === 0) {
        // !未加载路由先加载路由
        permissionStore
          .loadRoutes()
          .then(() => {
            homePath = permissionStore.asyncRoutes[0].path
            next({ path: homePath })
          })
          .catch(() => {
            next({ path: errorPath })
          })
      } else {
        // 是否跳转到登录页
        if ([loginPath, '/'].includes(to.path)) {
          next({ path: homePath })
        } else {
          tagStore.pushTag(to)
          next()
        }
      }
    } else {
      // !无token 未登录
      console.log('❎ 当前账号未登录')
      if (to.path !== loginPath) {
        next({ path: loginPath })
      } else {
        next()
      }
    }
  })

  router.afterEach(to => {
    setTitle(`${to.meta.title}` || '')
    if (to.path === errorPath) {
      NProgress.done()
    } else {
      NProgress.done()
    }
  })
}
